<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>位置追踪</title>
  <style>
    body {
      font-family: "微软雅黑", Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
    }
    nav {
      background-color: #333;
      padding: 10px 0;
      text-align: center;
    }

    nav ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
    }

    nav ul li {
      margin: 0 15px;
    }

    nav ul li a {
      color: white;
      text-decoration: none;
      font-size: 18px;
    }

    nav ul li a:hover {
      text-decoration: underline;
    }

    section {
      padding: 20px;
      margin: 20px;
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    h2 {
      color: #333;
    }

    .card {
      background-color: #f9f9f9;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    .card h3 {
      margin-top: 0;
      font-size: 20px;
    }

    .card p {
      margin: 10px 0;
      font-size: 16px;
    }

    .location-map {
      height: 600px;
      background-color: #e0e0e0;
      margin-top: 10px;
      border-radius: 8px;
    }

    .btn {
      display: inline-block;
      background-color: #4CAF50;
      color: white;
      padding: 10px 20px;
      text-align: center;
      border-radius: 5px;
      text-decoration: none;
    }

    .btn:hover {
      background-color: #45a049;
    }
  </style>
  <!-- 引入百度地图API -->
  <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=JNggynW1nmOY5TCPu9Fl127TFdytNBx6"></script>
</head>

<body>
  <!-- 导航栏保持不变 -->
  <nav>
    <ul style="display: flex; justify-content: flex-start; align-items: center; padding-left: 20px;">
      <li style="font-size: 18px; font-weight: bold; color: #fff; margin-right: 40px;">智能盲杖监测系统</li>
      <li><a href="index.html">首页</a></li>
      <li><a href="cane-management.html">盲杖管理</a></li>
      <li><a href="location-tracking.html">位置追踪</a></li>
      <li><a href="user-management.html">用户管理</a></li>
      <li><a href="alerts-notifications.html">报警和通知</a></li>
    </ul>
  </nav>

  <!-- 位置追踪内容 -->
  <section>
    <h2>位置追踪</h2>

    <div class="card" id="current-location-card">
      <h3>当前位置信息</h3>
      <p id="last-location">最后位置：加载中...</p>
      <p id="location-status">位置状态：加载中...</p>
      <p id="coordinates">经度：加载中, 纬度：加载中</p>
      <button class="btn" onclick="getLocation()">刷新位置</button>
    </div>

    <div class="card">
      <h3>步行导航</h3>
      <div class="input-group">
        <label for="startPoint">起点坐标（经度,纬度）:</label>
        <input type="text" id="startPoint" value="114.436597,30.418072" placeholder="例如：114.436597,30.418072">
      </div>
      <div class="input-group">
        <label for="endPoint">目的地坐标（经度,纬度）:</label>
        <input type="text" id="endPoint" placeholder="请输入目标坐标" value="114.44032,30.418984">
      </div>
      <div class="navigation-controls">
        <button class="btn" onclick="startNavigation()">开始步行导航</button>
        <button class="btn btn-secondary" onclick="clearRoute()">清除路线</button>
      </div>
      <div id="route-info" style="margin-top: 10px; font-size: 14px;"></div>
    </div>

    <!-- 地图容器 -->
    <div class="location-map" id="baidu-map"></div>

    <div class="card">
      <h3>历史位置记录</h3>
      <ul id="history-locations">
        <li>加载中...</li>
      </ul>
      <button class="btn" onclick="fetchHistoryData()">查看全部记录</button>
    </div>
  </section>

  <script>
    // 全局变量
    let map;
    let walking;
    let currentPositionMarker;
    let startMarker, endMarker;

    // 初始化地图
    function initMap() {
      map = new BMap.Map("baidu-map");
      const point = new BMap.Point(114.442512, 30.424093);
      map.centerAndZoom(point, 15);
      map.enableScrollWheelZoom(true);
      map.addControl(new BMap.NavigationControl());
      map.addControl(new BMap.ScaleControl());

      // 使用默认标记而不是自定义图标
      addMarker(point, "初始位置");
    }

    // 添加标记函数（简化版，不使用自定义图标）
    function addMarker(point, title) {
      const marker = new BMap.Marker(point);
      map.addOverlay(marker);

      const label = new BMap.Label(title, {
        offset: new BMap.Size(20, -10)
      });
      marker.setLabel(label);
      return marker;
    }

    // 定位功能
    function getLocation() {
      const geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function(r) {
        if (this.getStatus() === BMAP_STATUS_SUCCESS) {
          // 移除旧标记
          if(currentPositionMarker) {
            map.removeOverlay(currentPositionMarker);
          }

          // 添加新标记
          currentPositionMarker = addMarker(r.point, "我的位置");
          map.panTo(r.point);

          // 更新UI
          document.getElementById('last-location').textContent = `最后位置：${new Date().toLocaleString()}`;
          document.getElementById('location-status').textContent = `位置状态：定位成功`;
          document.getElementById('coordinates').textContent = `经度：${r.point.lng.toFixed(6)}, 纬度：${r.point.lat.toFixed(6)}`;

          // 自动更新起点坐标
          document.getElementById('startPoint').value = `${r.point.lng.toFixed(6)},${r.point.lat.toFixed(6)}`;
        } else {
          alert('定位失败，请检查设备权限或网络连接。');
          document.getElementById('location-status').textContent = `位置状态：定位失败`;
        }
      }, { enableHighAccuracy: true });
    }

    // 步行导航功能
    function startNavigation() {
      // 清除已有路线
      clearRoute();

      // 解析坐标
      const parseCoordinate = (str) => {
        const coords = str.split(',');
        if(coords.length !== 2) {
          throw new Error('坐标格式不正确，请使用"经度,纬度"格式');
        }
        const lng = parseFloat(coords[0].trim());
        const lat = parseFloat(coords[1].trim());
        if(isNaN(lng) || isNaN(lat)) {
          throw new Error('坐标必须是数字');
        }
        return new BMap.Point(lng, lat);
      };

      try {
        const startPoint = parseCoordinate(document.getElementById('startPoint').value);
        const endPoint = parseCoordinate(document.getElementById('endPoint').value);

        // 添加标记
        startMarker = addMarker(startPoint, "起点");
        endMarker = addMarker(endPoint, "终点");

        // 创建步行导航实例
        walking = new BMap.WalkingRoute(map, {
          renderOptions: {
            map: map,
            autoViewport: true
          },
          onSearchComplete: function(results) {
            const routeInfo = document.getElementById('route-info');
            if(walking.getStatus() === BMAP_STATUS_SUCCESS) {
              const plan = results.getPlan(0);
              const distance = (plan.getDistance() / 1000).toFixed(2);
              const duration = Math.ceil(plan.getDuration() / 60);

              // 显示路线信息
              routeInfo.innerHTML = `
                <p><strong>步行路线信息</strong></p>
                <p>起点：${document.getElementById('startPoint').value}</p>
                <p>终点：${document.getElementById('endPoint').value}</p>
                <p>全程约：${distance}公里</p>
                <p>预计需要：${duration}分钟</p>
              `;
            } else {
              routeInfo.innerHTML = '<p style="color:red;">路线规划失败，请检查坐标是否正确</p>';
            }
          }
        });

        // 执行搜索
        walking.search(startPoint, endPoint);
      } catch (error) {
        document.getElementById('route-info').innerHTML = `<p style="color:red;">${error.message}</p>`;
      }
    }

    // 清除路线功能
    function clearRoute() {
      if(walking) {
        map.clearOverlays();
        walking = null;

        // 重新添加当前位置标记
        if(currentPositionMarker) {
          map.addOverlay(currentPositionMarker);
        }

        document.getElementById('route-info').innerHTML = '';
      }
    }

    // 模拟数据获取函数
    async function fetchLocationData() {
      try {
        // 这里应该是实际的API调用
        // 模拟数据
        const mockData = {
          at: new Date().toISOString(),
          value: {
            longitude: 114.436597,
            latitude: 30.418072
          }
        };

        document.getElementById('last-location').textContent = `最后位置：${new Date(mockData.at).toLocaleString()}`;
        document.getElementById('location-status').textContent = `位置状态：模拟数据`;
        document.getElementById('coordinates').textContent = `经度：${mockData.value.longitude}, 纬度：${mockData.value.latitude}`;
      } catch (error) {
        console.error('Error fetching location data:', error);
      }
    }

    // 模拟历史数据获取
    async function fetchHistoryData() {
      try {
        // 这里应该是实际的API调用
        // 模拟数据
        const mockData = [
          { at: new Date(Date.now() - 3600000).toISOString(), value: { longitude: 114.435, latitude: 30.417 } },
          { at: new Date(Date.now() - 7200000).toISOString(), value: { longitude: 114.434, latitude: 30.416 } },
          { at: new Date(Date.now() - 10800000).toISOString(), value: { longitude: 114.433, latitude: 30.415 } }
        ];

        const historyList = document.getElementById('history-locations');
        historyList.innerHTML = '';

        mockData.forEach(point => {
          const li = document.createElement('li');
          li.textContent = `${new Date(point.at).toLocaleString()} - 位置：${point.value.longitude.toFixed(6)}, ${point.value.latitude.toFixed(6)}`;
          historyList.appendChild(li);
        });
      } catch (error) {
        console.error('Error fetching history data:', error);
      }
    }

    // 页面加载时初始化
    window.onload = function() {
      initMap();
      getLocation();
      fetchLocationData();
      fetchHistoryData();
    };
  </script>
</body>
</html>